﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSLib.Parsing.Common;

namespace PSLib.Parsing.Lua.ObjectModel
{
    internal static class Helper
    {
        internal static void AssignVariableDefinition(IList<Variable> vars, IList<ValueReferenceRevision> valRefs)
        {
            if (vars == null || valRefs == null) return;
            for (int i = 0; i < vars.Count; i++)
            {
                if (vars[i] != null)
                {
                    if (i < valRefs.Count) vars[i].SetValue(valRefs[i]);
                }
            }
        }

        internal static string TrimStringToVariableName(string value)
        {
            string result = value;
                 
            if (value.StartsWith("\"")) result = value.Trim('\"');
            else if (value.StartsWith("\'")) result = value.Trim('\'');
            else if(value.StartsWith("["))
            {
                int indexOfSecondBracket = value.IndexOf('[', 1);
                if (indexOfSecondBracket != -1)
                {
                    result = value.Substring(indexOfSecondBracket + 1, value.Length - (indexOfSecondBracket + 1) * 2);
                }
            }
            return result;
        }

        internal static Variable GetTableVariable(ValueReference baseValueReference, string key, bool createBlankIfNotExistsInTable = true)
        {
            Variable result = null;

            if (baseValueReference != null && !string.IsNullOrEmpty(key))
            {
                Metatable table = baseValueReference.Value as Metatable;
                if (table != null)
                {
                    if (table.Contains(key)) result = table[key];
                    else if (createBlankIfNotExistsInTable)
                    {
                        result = new Variable();
                        result.Name = key;
                        table[key] = result;
                    }
                }
            }
            return result;
        }
    }
}
